﻿using Microsoft.Extensions.Options;
using Volo.Abp;
using Volo.Abp.Http.Client.DynamicProxying;
using Volo.Abp.Http.Modeling;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Tracing;
using Qianke.Core.Common;

namespace Qianke.Core.Saas.HttpApi.Client.Common
{
    public class MyApiDescriptionFinder : ApiDescriptionFinder
    {
        public MyApiDescriptionFinder(IApiDescriptionCache cache, IOptions<AbpCorrelationIdOptions> abpCorrelationIdOptions, ICorrelationIdProvider correlationIdProvider, ICurrentTenant currentTenant)
            : base(cache, abpCorrelationIdOptions, correlationIdProvider, currentTenant)
        {
        }

        protected override async Task<ApplicationApiDescriptionModel> GetApiDescriptionFromServerAsync(
      HttpClient client,
      string baseUrl)
        {
            var requestMessage = new HttpRequestMessage(
                HttpMethod.Get,
                baseUrl.EnsureEndsWith('/') + "api/abp/api-definition"
            );

            AddHeaders(requestMessage);
            var response = await client.SendAsync(
                requestMessage,
                CancellationTokenProvider.Token
            );

            if (!response.IsSuccessStatusCode)
                throw new AbpException("Remote service returns error! StatusCode = " + response.StatusCode);

            var content = await response.Content.ReadAsStringAsync();
            
            return content.ToObject<ApplicationApiDescriptionModel>();
        }

    }
}
